package org.smile.tomcat.session.redis;

import java.io.IOException;
import java.util.Enumeration;

import org.apache.catalina.Manager;
import org.apache.catalina.session.StandardSession;
/**
 * 使用redis实现持久化的session实现
 * @author 胡真山
 *
 */
public class RedisSession extends StandardSession {

	/**持久化实现*/
	protected RedisStore store;

	public RedisSession(Manager manager) {
		super(manager);
	}

	public RedisStore getStore() {
		return store;
	}

	public void setStore(RedisStore store) {
		this.store = store;
	}
	
	@Override
	public void setId(String id) {
		this.id=id;
	}
	
	@Override
	public Enumeration<String> getAttributeNames() {
		return this.store.getAttributeNames(this);
	}

	@Override
	public void invalidate() {
		expire();
		this.store.remove(this.getId());
	}

	@Override
	public void setAttribute(String name, Object value) {
		Object oldValue = getAttribute(name);
		super.setAttribute(name, value);
		if (value == null && oldValue != null) {
			store.removeAttrubite(this, name);
		} else if (value != null) {
			store.setAttrubite(this, name,value);
		}
	}
	/**
	 * 当session的数据存贮发生变化时
	 * @param name
	 * @param datas
	 */
	protected void onAttrubiteStoreChange(String name, byte[] datas){
		
	}
	/**
	 * 在一次请求之后处理
	 */
	protected void afterRequest(){
		
	}
	/**
	 * 设置属性值 不进行持久化
	 * @param name
	 * @param value
	 */
	protected void setValue(String name, Object value){
		super.setAttribute(name, value);
	}
	
	@Override
	public Object getAttribute(String name) {
		Object value= super.getAttribute(name);
		if(value==null){
			value= store.getAttrubite(this, name);
			if(value!=null){
				super.setAttribute(name, value);
			}
		}
		return value;
	}

	@Override
	 public void access() {
		 super.access();
		 store.access(this);
	 }

	@Override
	public void removeAttribute(String name) {
		super.removeAttribute(name);
		store.removeAttrubite(this, name);
	}

	@Override
	public void writeObjectData(java.io.ObjectOutputStream out) throws IOException {
		super.writeObjectData(out);
		out.writeLong(this.getCreationTime());
	}

	@Override
	public void readObjectData(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
		super.readObjectData(in);
		this.setCreationTime(in.readLong());
	}
	
}
